<template>
  <div class="appendChatDialog" v-loading="loading">
    <el-dialog
      title="图表设置"
      v-model="visible"
      width="640px"
      :show-close="true"
      @close="Closed()">
      <div class="content">
        <el-form label-position="top" label-width="80px" :model="form" ref="form" :rules="rules">
          <el-form-item label="关联报表" prop="reportAnalysisId">
            <el-select v-model="form.reportAnalysisId" filterable clearable placeholder="请选择" @change="handleChangeReport" style="width: 420px;">
              <el-option
                v-for="item in reportOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="图表展示名称" prop="name">
            <el-input v-model="form.name" clearable maxlength="20" style="width: 420px;"></el-input>
          </el-form-item>
          <el-form-item label="图表展示类型:" prop="type">
            <el-radio-group v-model="form.type" @change="handleClickChangeChartRadio">
              <!-- <el-radio :label="'miniIndicator'" v-if="reportLinkChart.includes('miniIndicator')">小指标</el-radio> -->
              <el-radio :label="'indicator'" v-if="reportLinkChart.includes('indicator')">指标</el-radio>
              <el-radio :label="'line'" v-if="reportLinkChart.includes('line')">线图</el-radio>
              <el-radio :label="'bar'" v-if="reportLinkChart.includes('bar')">柱图</el-radio>
              <el-radio :label="'ranking'" v-if="reportLinkChart.includes('ranking')">排行</el-radio>
              <el-radio :label="'pie'" v-if="reportLinkChart.includes('pie')">饼图</el-radio>
              <el-radio :label="'table'" v-if="reportLinkChart.includes('table')">表格</el-radio>
              <el-radio :label="'lineTrend'" v-if="reportLinkChart.includes('lineTrend')">指标卡趋势图</el-radio>
              <el-radio :label="'funnel'" v-if="reportLinkChart.includes('funnel')">漏斗图</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="同时显示:" v-if="isShowTimeDime" prop="isTiDimeValue">
            <el-checkbox v-model="form.isTiDimeValue" label="时间维度" size="large" @change="handleChangeTimeValue"/>
          </el-form-item>
          <el-form-item label="数据展示条数:" v-if="isShowDataNum" prop="size">
            <el-select v-model="form.size" placeholder="请选择" style="width: 120px;">
              <el-option
                v-for="item in showDataOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="卡片布局:" prop="layout">
            <div class="cardSize">
              <div class="cardSize-top">
                <p class="item" v-for="(item, index) in cardOptions" :key="index">
                  <img :class="{'gary': item.isDisabled}" :src="item.img" alt="">
                  <span class="spanRadio">
                    <el-radio v-model="form.layout" :disabled="item.isDisabled" :label="item.label">{{ item.radio }}</el-radio>
                  </span>
                </p>
              </div>
            </div>
          </el-form-item>
          <div class="perch" style="width: 100%;height: 30px;"></div>
          <!-- 日期范围类型 -->
          <el-form-item label="时段类型:" prop="radio">
            <el-radio-group v-model="radio" size="medium" @change="handleChangeRadio">
              <el-radio label="1" border>相对时段</el-radio>
              <el-radio label="2" border>固定时段</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="radio === '1'" label="相对时段范围:" prop="relativelyTime" style="width: 420px;">
            <el-select v-model="form.relativelyTime" clearable placeholder="请选择">
              <el-option
                v-for="item in relativelyTimeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="radio === '2'" label="固定时段范围:" prop="time" style="width: 420px;">
            <el-date-picker
              v-model="form.time"
              value-format="YYYY-MM-DD"
              type="daterange"
              unlink-panels
              range-separator="~"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :shortcuts="shortcuts"
              :size="size"
              @change="handleChangeTime"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="footer">
          <el-button size="mini" @click="Closed">取消</el-button>
          <el-button size="mini" type="primary" @click="handleClickConfirm('form')">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// vuex
import store from "@/store";
// 图片
import minisize from '@/assets/dataCenter/dataBoard_mini.png';
import smallsize from '@/assets/dataCenter/dataBoard_small.png';
import mediumsize from '@/assets/dataCenter/dataBoard_medium.png';
// API
import {
  dataBoardReportList,
  dataBoardInsertChart,
  dataBoardByChartId,
  dataBoardUpdateChart
} from '@/api/dataCenter/dataBoard.js'
// utils
import { dateStrChangeTimeTamp } from './utils.js'
export default {
  name: 'AppendChatDialog',
  props: {
    visible: {
      type: Boolean,
      default: () => {
        return false;
      }
    },
    id: {
      type: Number,
      default: () => {
        return null;
      }
    }
  },
  data() {
    return {
      loading: false,
      radio: '1',
      form: {
        name: '',
        reportAnalysisId: null,
        billboardId: null,
        insId: null,
        isTiDime: 0,
        isTiDimeValue: false,
        sort: 1,
        size: null,
        type: '',
        layout: '',
        status: 1,
        id: null,
        merchantId: '',
        time: [],
        startTime: '',
        endTime: '',
        createTime: null,
        updateTime: null,
        deleted: null,
        relativelyTime: 604800000
      },
      rules: {
        reportAnalysisId: [{ required: true, message: '请选择关联报表', trigger: 'change' }],
        name: [{ required: true, message: '请输入图标展示名称', trigger: 'blur' }],
        time: [{ required: true, message: '请选择固定时间段', trigger: 'change' }],
        relativelyTime: [{ required: true, message: '请选择相对时间段', trigger: 'change' }],
        type: [{ required: true, message: '请选择图表类型', trigger: 'change' }],
        size: [{ required: true, message: '请选择数据展示条数', trigger: 'change' }],
      },
      reportOptions: [],
      showDataOptions: [
        {
          value: 1,
          label: 'Top5'
        },
        {
          value: 2,
          label: 'Top10'
        }
      ],
      relativelyTimeOptions: [
        {
          value: 0,
          label: '今天'
        },
        {
          value: 3600 * 1000 * 24 * 1,
          label: '昨天'
        },
        {
          value: 3600 * 1000 * 24 * 7,
          label: '过去7天'
        },
        {
          value: 3600 * 1000 * 24 * 14,
          label: '过去14天'
        },
        {
          value: 3600 * 1000 * 24 * 30,
          label: '过去30天'
        },
        {
          value: 3600 * 1000 * 24 * 90,
          label: '过去90天'
        },
        {
          value: 3600 * 1000 * 24 * 180,
          label: '过去180天'
        },
        {
          value: 3600 * 1000 * 24 * 365,
          label: '过去365天'
        },
      ],
      cardOptions: [
        {
          img: minisize,
          isDisabled: true,
          label: 'mini',
          radio: '小尺寸'
        },
        {
          img: smallsize,
          isDisabled: true,
          label: 'small',
          radio: '中尺寸'
        },
        {
          img: mediumsize,
          isDisabled: true,
          label: 'medium',
          radio: '大尺寸'
        }
      ],
      isShowTimeDime: false,
      isShowDataNum: false,
      size: '' | 'large' | 'small',
      shortcuts: [
        {
          text: '昨天',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
            return [start, end]
          },
        },
        {
          text: '过去7天',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
          },
        },
        {
          text: '过去14天',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 14)
            return [start, end]
          },
        },
        {
          text: '过去30天',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
          },
        },
        {
          text: '过去2个月',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 60)
            return [start, end]
          },
        },
        {
          text: '过去3个月',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
          },
        },
        {
          text: '过去6个月',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 180)
            return [start, end]
          },
        },
        {
          text: '过去12个月',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
            return [start, end]
          },
        },
      ],
      reportLinkChart: ['miniIndicator', 'indicator', 'line', 'bar', 'ranking', 'pie', 'table', 'lineTrend', 'funnel']
    }
  },
  watch: {
    visible: {
      handler(val) {
        if(val && !this.id) {
          console.log('visibile')
          this.$nextTick(() => {
            this.$refs.form.resetFields();
            this.cardOptions.forEach(item => {
              item.isDisabled = true;
            })
            this.radio = '1';
            this.form.time = [];
            this.form.relativelyTime = 604800000;
            this.isShowTimeDime = false;
            this.isShowDataNum = false;
            this.reportLinkChart = ['miniIndicator', 'indicator', 'line', 'bar', 'ranking', 'pie', 'table', 'lineTrend', 'funnel'];
          })
        }
      },
      deep: true
    },
    id: {
      handler(val) {
        if(val) {
          console.log('id')
          this.dataBoardByChartIdApi();
        }
      },
      deep: true
    }
  },
  mounted() {
    this.form.merchantId = store.state.user.merchantId;
    this.form.insId = store.state.insId.insId;
    this.dataBoardReportListApi();
  },
  methods: {
    // 获取图表详情Api
    async dataBoardByChartIdApi() {
      let res = await dataBoardByChartId({
        id: this.id
      });
      if(res.code === 200) {
        this.form = res.payload;
        if(this.form.relativelyTime) {
          this.radio = '1';
        } else {
          this.radio = '2';
        }
        if(this.form.isTiDime === 1) {
          this.form.isTiDimeValue = true;
        } else {
          this.form.isTiDimeValue = false;
        }
        this.form.time = [new Date(this.form.startTime).format("yyyy-MM-dd"), new Date(this.form.endTime).format("yyyy-MM-dd")];
        this.handleClickChangeChartRadio(this.form.type, this.form.layout);

        this.reportOptions.forEach(item => {
          if(this.form.reportAnalysisId === item.id) {
            this.reportLinkChart = item.type.split(',');
          }
        })
        // 判断type类型
        if(this.form.type === 'bar') {
          this.isShowTimeDime = true;
        } else if(this.form.type === 'ranking' || this.form.type === 'pie' || this.form.type === 'funnel') {
          this.isShowDataNum = true;
        }
      }
    },
    // 修饰关闭dialog
    Closed() {
      this.$emit('update:visible', false);
    },
    // 关联报表change
    handleChangeReport(val) {
      if(val) {
        this.reportOptions.forEach(item => {
          if(val === item.id) {
            this.reportLinkChart = item.type.split(',');
            this.form.name = item.name
          }
        })

      } else {
        this.reportLinkChart = ['miniIndicator', 'indicator', 'line', 'bar', 'ranking', 'pie', 'table', 'lineTrend', 'funnel'];
        this.form.name = '';
      }
    },
    // 切换固定时段和相对时段
    handleChangeRadio(val) {
      if(val === '1') {
        this.form.time = [];
        this.form.startTime = null;
        this.form.endTime = null;
        // 默认相对七天
        this.form.relativelyTime = 604800000;
      } else {
        this.form.relativelyTime = null;
      }
    },
    // 时间段
    handleChangeTime(val) {
      this.form.startTime = dateStrChangeTimeTamp(val[0]);
      this.form.endTime = dateStrChangeTimeTamp(val[1]);
    },
    // 关联报表list Api
    async dataBoardReportListApi() {
      let res = await dataBoardReportList({
        id: store.state.user.merchantId
      });
      if(res.code === 200) {
        this.reportOptions = res.payload;
      }
    },
    // 选择图表类型
    handleClickChangeChartRadio(val, layout) {
      // 置空数据
      this.form.layout = null;
      this.isShowDataNum = false;
      this.isShowTimeDime = false;

      if(val === 'indicator' || val === 'miniIndicator') { // 指标
        this.cardOptions.forEach(item => {
          if(item.label === 'mini') {
            item.isDisabled = false;
          } else {
            item.isDisabled = true;
          }
        })
        // 默认选中
        this.form.layout = 'mini';
      } else if(val === 'line' || val === 'bar' ) { // 线图
        this.cardOptions.forEach(item => {
          if(item.label === 'mini') {
            item.isDisabled = true;
          } else {
            item.isDisabled = false;
          }
        })
        // 默认选中
        this.form.layout = 'small';
      } else if(val === 'ranking' || val === 'pie' || val === 'funnel') {
        this.isShowDataNum = true;
        this.cardOptions.forEach(item => {
          if(item.label === 'mini') {
            item.isDisabled = true;
          } else {
            item.isDisabled = false;
          }
        })
        // 默认选中
        this.form.layout = 'small';
      } else if(val === 'table') {
        this.isShowTimeDime = true;
        this.cardOptions.forEach(item => {
          if(item.label === 'mini') {
            item.isDisabled = true;
          } else {
            item.isDisabled = false;
          }
        })
        // 默认选中
        this.form.layout = 'small';
      } else {
        this.cardOptions.forEach(item => {
          if(item.label === 'medium') {
            item.isDisabled = false;
          } else {
            item.isDisabled = true;
          }
        })
        // 默认选中
        this.form.layout = 'medium';
      }
      // 编辑时默认选中
      if(layout) {
        // 默认选中
        this.form.layout = layout;
      }
    },
    // 是否保留时间维度
    handleChangeTimeValue(val) {
      if(val) {
        this.form.isTiDime = 1;
      } else {
        this.form.isTiDime = 0;
      }
    },
    // 选择尺寸
    handleClickChangeSizeRadio() {

    },
    // 确定
    handleClickConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(!this.id) {
            this.dataBoardInsertChartApi();
          } else {
            this.dataBoardUpdateChartApi();
          }
        } else {
          return false;
        }
      });
    },
    // 新增图表Api
    async dataBoardInsertChartApi() {
      this.loading = true;
      delete this.form.time;
      // 获取全局菜单ID
      this.form.billboardId = store.state.user.currentMenuId;
      let res = await dataBoardInsertChart(this.form);
      if(res.code === 200) {
        this.form.id = res.payload;
        this.$emit('handleClickConfirm', this.form);
        this.loading = false;
        this.Closed();
      }
    },
    // 编辑图表Api
    async dataBoardUpdateChartApi() {
      this.loading = true;
      // 获取全局菜单ID
      this.form.billboardId = store.state.user.currentMenuId;
      let res = await dataBoardUpdateChart(this.form);
      if(res.code === 200) {
        this.$emit('handleClickConfirm', this.form, true); // true代表编辑
        this.loading = false;
        this.Closed();
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.appendChatDialog {
  .cardSize {
    width: 100%;
    height: 100px;
    &-top {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10px;
      .item {
        width: 190px;
        height: 100%;
        cursor: pointer;
        img {
          width: 100%;
          height: 100%;
        }
        .gary {
          opacity: .2;
          pointer-events: none;
        }
        .spanRadio {
          width: 100%;
          height: 20px;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }
  }
}
</style>

<style lang="scss">
.appendChatDialog {
  .el-dialog__header {
    padding: 10px 0 10px 24px;
    background: #F7F8FA;
    border: none;
    margin: 0;
    .el-dialog__title {
      color: #252934;
      font-size: 14px;
      line-height: 22px;
      word-wrap: break-word;
    }
    .el-dialog__headerbtn {
      width: 44px;
      height: 44px;
      top: 0;
      right: 0;
      .el-dialog__close {
        color: inherit;
      }
    }
  }
  .el-dialog__body {
    padding: 20px;
    .el-form-item {
      margin-bottom: 24px;
    }
    .el-form-item__label {
      font-size: 14px;
      color: #6b798e;
      margin-bottom: 4px !important;
    }
    .el-radio {
      // width: 56px;
      // height: 18px;
      margin-right: 8px;
    }
  }
}
</style>